import React from "react";
import { Chesstype, GameStatus } from "../types/enums";
import { Board } from "./Board";
import { GameStatusComp } from "./GameStatusComp";

interface IState {
  chesses: Chesstype[]
  gameStatus: GameStatus
  num: number
  cellW: number
  nextChess: Chesstype.red | Chesstype.blue
}
export class Game extends React.Component<{}, IState> {
  componentDidMount() {
    this.init()
  }

  init() {
    const len = this.state.num ** 2, arr: Chesstype[] = []
    for (let i = 0; i < len; i++) {
      arr.push(Chesstype.none)
    }
    this.setState({
      chesses: arr,
      gameStatus: GameStatus.gaming
    })
  }

  state: IState = {
    num: 3, // 布局 3x3
    cellW: 50, // 格子宽度
    chesses: [],
    gameStatus: GameStatus.gaming,
    nextChess: Chesstype.red
  }

  /**
   * 处理点击事件
   * @param i 
   */
  handle(i: number) {
    console.log('handle', i)
    const { chesses, nextChess } = this.state;
    chesses[i] = this.state.nextChess;
    this.setState({
      nextChess: nextChess === Chesstype.red ? Chesstype.blue : Chesstype.red,
      chesses: chesses,
      gameStatus: this.getStatus(chesses, i)
    })
    console.log(this.getStatus(chesses, i))
  }

  getStatus(chesses: Chesstype[], i: number): GameStatus {
    // 是否有一方获取胜利
    const horMin = Math.floor(i / 3) * 3;
    const verMin = i % 3;
    if (
      (
        // 横向
        chesses[horMin] === chesses[horMin + 1] &&
        chesses[horMin] === chesses[horMin + 2]
      ) || (
        // 垂直
        chesses[verMin] === chesses[verMin + 3] &&
        chesses[verMin] === chesses[verMin + 6]
      ) || (
        // 斜线
        (chesses[0] !== Chesstype.none && chesses[0] === chesses[4] && chesses[0] === chesses[8]) ||
        (chesses[2] !== Chesstype.none && chesses[2] === chesses[4] && chesses[2] === chesses[6])
      )
    ) {
      return chesses[i] == Chesstype.red ? GameStatus.redWin : GameStatus.blueWin
    }
    // 是否平局
    if (!chesses.includes(Chesstype.none)) {
      return GameStatus.equal
    }
    return GameStatus.gaming
  }

  render() {
    return (
      <div className="game" style={{textAlign:'center'}}>
        <h1>三联棋</h1>
        <GameStatusComp
          next={this.state.nextChess}
          type={this.state.gameStatus} />
        <Board
          over={this.state.gameStatus !== GameStatus.gaming}
          chesses={this.state.chesses}
          onClick={this.handle.bind(this)} />
        <button onClick={()=>{
          this.init()
        }}>重新开始</button>
      </div>
    )
  }
}

